﻿using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using ArcEngine.Resources;


namespace ArcEngine.Editor.Wizards
{
	public partial class ImportGIFAnimationWizard : Form
	{
		public ImportGIFAnimationWizard()
		{
			InitializeComponent();
		}



		/// <summary>
		/// 
		/// </summary>
		/// <param name="o"></param>
		/// <param name="e"></param>
		private void OnFrameChanged(object o, EventArgs e)
		{
			PreviewBox.Invalidate();
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void LoadGIFButton_Click(object sender, EventArgs e)
		{
			if (OpenDlg.ShowDialog() != DialogResult.OK)
				return;

			Bmp = Bitmap.FromFile(OpenDlg.FileName);


			ImageAnimator.Animate(Bmp, new EventHandler(this.OnFrameChanged));

		}



		/// <summary>
		/// AnimationBox OnPaint
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void PreviewBox_Paint(object sender, PaintEventArgs e)
		{
			if (Bmp == null)
				return;

			ImageAnimator.UpdateFrames();
			e.Graphics.DrawImage(Bmp, new Point(0, 0));
		}




		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnFormClosing(object sender, FormClosingEventArgs e)
		{
			if (DialogResult != DialogResult.OK)
				return;

			// No animation loaded ?
			if (Bmp == null)
			{
				MessageBox.Show("Select an animation first !");
				e.Cancel = true;
				return;
			}


			// Anim already exists ?
			if (string.IsNullOrEmpty(AnimNameBox.Text) ||  ResourceManager.GetAnimation(AnimNameBox.Text) != null)
			{
				MessageBox.Show("Animation name already in use or invalid. Use another name !");
				e.Cancel = true;
				return;
			}


			// Create the TileSet
			TileSet tileset = ResourceManager.CreateTileSet(AnimNameBox.Text);
			if (tileset == null)
			{
				MessageBox.Show("Failed to create Tileset !");
				return;
			}
			tileset.TextureName = AnimNameBox.Text;


			// Create the animation
			Animation anim = ResourceManager.CreateAnimation(AnimNameBox.Text);
			anim.TileSetName = AnimNameBox.Text;

	
			
			// Final bitmap
			Bitmap FinalBmp = new Bitmap(512, 512);
			System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(FinalBmp);

			// Get the number of frame
			System.Drawing.Imaging.FrameDimension dim = new System.Drawing.Imaging.FrameDimension(Bmp.FrameDimensionsList[0]);
			int framecount = Bmp.GetFrameCount(dim);

			// Location of the next bitmap to paste
			Point pos = Point.Empty;

			// Maximum height
			int maxheight = 0;

			// Extract all frame
			for (int id = 0; id < framecount; id++)
			{
				// Select the good frame
				Bmp.SelectActiveFrame(dim, id);


				// Over limits ?
				if (pos.X + Bmp.Width > FinalBmp.Width)
				{
					pos.X = 0;
					pos.Y += maxheight;

					maxheight = 0;
				}

				// Maximum height, to avoid overlapping tiles
				maxheight = Math.Max(maxheight, Bmp.Height);

				// Paste it on the final image
				gfx.DrawImage(Bmp, pos);


				// Adds the tile
				Tile tile = tileset.AddTile(id);
				tile.Rectangle = new Rectangle(pos, Bmp.Size);

				anim.Tiles.Add(id);

				// Move to the next free space
				pos.X += Bmp.Width;
			}



			// Add the texture as a binary
			FinalBmp.Save("final.png", ImageFormat.Png);
			string binname = AnimNameBox.Text;
			if (!binname.EndsWith(".png"))
				binname += ".png";
			Binary bin = ResourceManager.CreateBinary(binname);
			if (bin == null)
			{
				Log.Send(new LogEventArgs(LogLevel.Error, "Failed to create binary \"" + binname + "\" !", null));
				return;
			}
			MemoryStream ms = new MemoryStream();
			using (ms)
			{
				FinalBmp.Save(ms, ImageFormat.Png);
				bin.Data = ms.ToArray();
			}



			// Create the final texture
			Texture texture = ResourceManager.CreateTexture(AnimNameBox.Text);
			if (texture != null)
			{
				binname = AnimNameBox.Text;
				if (!binname.EndsWith(".png"))
					binname += ".png";

				texture.LoadImage(binname);
			}
			






			

		}




		#region Properties




		/// <summary>
		/// Bitmap image
		/// </summary>
		Image Bmp;

		#endregion
	}
}
